/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.util.properties.formatters.impl;

import com.mytdev.util.properties.formatters.Formatter;
import java.awt.Dimension;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Yann D'Isanto
 */
public class DimensionFormatter implements Formatter<Dimension> {

    private static final Pattern DIMENSION_PATTERN = Pattern.compile("(\\d+) +(\\d+)");

    /**
     * Parses a Dimension from the specified string then returns it.
     *
     * @param string the string to parse.
     * @return the parsed Dimension.
     * @throws ParseException if an error occurs.
     */
    public Dimension parse(String string) throws ParseException {
        Matcher matcher = DIMENSION_PATTERN.matcher(string);
        if (!matcher.matches()) {
            throw new ParseException("invalid dimension: " + string, 0);
        }
        return new Dimension(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)));
    }

    /**
     * Formats the specified Dimension as a string representation.
     *
     * @param dimension the Dimension to format
     * @return the Dimension string representation or null if the specified
     * Dimension is null.
     */
    public String format(Dimension dimension) {
        if (dimension == null) {
            return null;
        }
        return new StringBuilder().append(dimension.width).
                append(" ").
                append(dimension.height).toString();
    }
}
